/*
 * For com.royal.art
 * Copyright [2015/11/15] By FCHEN
 */
package com.lerning.edu.manage.controller;

import com.google.common.collect.Lists;
import com.lerning.edu.beans.SysRole;
import com.lerning.edu.beans.SysUser;
import com.lerning.edu.beans.page.PageList;
import com.lerning.edu.commons.PwdUtils;
import com.lerning.edu.commons.util.StringUtil;
import com.lerning.edu.manage.util.UserUtils;
import com.lerning.edu.services.SysUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * SysUserController
 *
 * @author FCHEN
 * @date 2015/11/15
 */
@Controller
@RequestMapping("sysuser")
public class SysUserController extends BaseController {

    @Autowired
    private SysUserService sysUserService;

    @ModelAttribute("sysUser")
    public SysUser get(@RequestParam(required=false) Long id) {
        if ( id != null ){
            return UserUtils.get(id);
        }else{
            return new SysUser();
        }
    }

    /**
     * 查询列表
     * @param sysUser
     * @return
     */
    @RequiresPermissions("sys:user:view")
    @RequestMapping(value = {"","/","list"})
    public String list(SysUser sysUser,HttpServletRequest request){
        request.setAttribute("sysUser",sysUser);
        return "sys/sysuser/list";
    }

    /**
     * 异步获取list资源
     * @param pageList
     * @param sysUser
     * @return
     */
    @RequiresPermissions("sys:user:view")
    @RequestMapping("asynList")
    @ResponseBody
    public PageList asynList(PageList pageList, SysUser sysUser){
       
        return sysUserService.queryPage(pageList,sysUser);    }


    /**
     * 新增修改
     * @param sysUser
     * @return
     */
    @RequiresPermissions("sys:user:edit")
    @RequestMapping(value = {"add","edit"},method = RequestMethod.GET)
    public String edit(SysUser sysUser, Model model){
        model.addAttribute("sysUser",sysUser);
        model.addAttribute("allRoles",UserUtils.getRoleList());
        return "sys/sysuser/edit";
    }

    @RequiresPermissions("sys:user:edit")
    @RequestMapping(value = "save",method = RequestMethod.POST )
    public String save(SysUser sysUser){
        sysUser.setOperator(UserUtils.getUser().getId());
        // 如果新密码为空，则不更换密码
        if (StringUtil.isNotBlank(sysUser.getPwd())) {
            if( sysUser.getSalt() == null || sysUser.getSalt().isEmpty() ) {
                sysUser.setSalt(PwdUtils.getSalt());
            }
            sysUser.setPwd(PwdUtils.saltPwd(sysUser.getPwd(),sysUser.getSalt()));
        }
        // 角色数据有效性验证，过滤不在授权内的角色
        List<SysRole> roleList = Lists.newArrayList();
        List<Long> roleIdList = sysUser.getRoleIdList();
        for (SysRole r : UserUtils.getRoleList()){
            if (roleIdList.contains(r.getId())){
                roleList.add(r);
            }
        }

        sysUser.setRoleList(roleList);
        if ( sysUser.getId() == null ){
            sysUserService.add(sysUser);
        } else {
            sysUserService.update(sysUser);
            // 清除老的用户与角色关联
            sysUserService.deleteUserRole(sysUser);
        }
        // 保存用户与角色关联
        if (sysUser.getRoleList() != null && sysUser.getRoleList().size() > 0){
            sysUserService.insertUserRole(sysUser);
        }

        UserUtils.clearCache(sysUser);
        // 清除当前用户缓存
        if (sysUser.getAccount().equals(UserUtils.getUser().getAccount())){
            UserUtils.clearCache();
        }
        //TODO  成功失败结果页面
        return "redirect:list";
    }

    @RequiresPermissions("sys:user:delete")
    @RequestMapping("delete")
    @ResponseBody
    public Object delete(Long id,HttpServletRequest request){
        SysUser sysUser = new SysUser();
        sysUser.setId(id);
        sysUser.setOperator(UserUtils.getUser().getId());
        int result = sysUserService.delete(sysUser);
        //TODO  成功失败结果页面
        return result;
    }

    /**
     * 验证登录名是否有效
     * @param oldAccount
     * @param account
     * @return
     */
    @ResponseBody
    @RequiresPermissions("sys:user:edit")
    @RequestMapping(value = "checkAccount", method = RequestMethod.POST)
    public Boolean checkAccount(String oldAccount, String account) {
        if (account !=null && account.equals(oldAccount)) {
            return Boolean.TRUE;
        } else if (account !=null && sysUserService.queryUserByAccount(account) == null) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }


}
